<!--suppress ALL -->
<script setup lang="ts">

import { ref } from 'vue'
import { ElMessage } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadProps, UploadRawFile, UploadInstance } from 'element-plus'
import {uploads} from '@/api/uploader';
import type { AssetMetadata } from "@/types/AssetMetadata";
// import {  assetUpdate } from "@/api/home";
const props = defineProps({
    uploadButtonText: {
      type: String,
      default: ''
    },
    isItEncrypted: {
      type: Boolean,
      default: false
    },
    namespaceId: {
        type: String,
        default: ''
    },
    fileList: {
        type: Array,
        default: []
    },
})

const emit = defineEmits(['fileChange', 'uploadSuccess']);
const uploadRef = ref<UploadInstance>();
const selectedFiles = ref<UploadRawFile[]>([]);
const uploadProgress = ref<number[]>([]);
const isUploading = ref(false);

// 手动上传
const submitUpload = async () => {
    if (selectedFiles.value.length) {
        isUploading.value = true;
        uploadProgress.value = new Array(selectedFiles.value.length).fill(0);

        for (let i = 0; i < selectedFiles.value.length; i++) {
            const file: any = selectedFiles.value[i];

            try {
                await uploadFile(file.raw, i);
            } catch (error) {
                console.log(`文件 ${file.name} 上传失败: ${error}`);
            }
        }

        isUploading.value = false;
        selectedFiles.value = []; // 清空已选文件
        uploadProgress.value = []; // 清空上传进度
        uploadRef.value!.clearFiles(); // 清空已上传的文件列表
        
        // ElMessage.success('全部文件上传完成');
    } else {
        ElMessage.warning(`请先选择文件`);
    }
}

// 上传单个文件
const uploadFile = async (rawFile: UploadRawFile, index: number) => {
    try {
        // 模拟上传进度
        for (let progress = 0; progress <= 100; progress += 10) {
            await new Promise(resolve => setTimeout(resolve, 200)); // 模拟延迟
            uploadProgress.value[index] = progress; // 更新进度条
        }

        console.log(props.namespaceId, "上传文件参数==isItEncrypted", props?.isItEncrypted);
          // await assetUpdate();

       await uploads(props.namespaceId, rawFile, props?.isItEncrypted,()=>{
         emit('uploadSuccess', true);
        console.log('hz')
       })
      
    } catch (error) {
        console.log(error);
    }
}

// 删除文件
const handleRemove: UploadProps['onRemove'] = (_file, uploadFiles) => {
    // selectedFiles.value = uploadFiles;
    emit('fileChange', uploadFiles);
}

// 文件超出限制
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
    ElMessage.warning(`限制为9，您这次选择了 ${files.length} 个文件，加起来有 ${files.length + uploadFiles.length}`)
}

// 文件上传前的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // if (rawFile.size / 1024 / 1024 > 30) {
    //     ElMessage.error('文件大小不能超过30M')
    //     return false;
    // }
    if (props.namespaceId == '') {
        ElMessage.error('请先选择命名空间!');
        return false;
    }
    const fileName = rawFile.name;
    interface FileItem {
      name: string
      [key: string]: unknown
    }
    const fileList = props.fileList.filter((item: FileItem) => item.name == fileName);
    if (fileList.length) {
        ElMessage.error('请勿重复上传!');
        return false;
    }
    return true;
}

// 文件选择变化
const handleChange: any = async (file: UploadRawFile, uploadFiles: any[]) => {
    if (beforeAvatarUpload(file)) {
        selectedFiles.value = uploadFiles;
        // 自动开始上传
        await submitUpload();
    } else {
        uploadFiles.splice(uploadFiles.length - 1, 1);
    }
}



</script>

<template>
    <div class="upload-container">
     
        <el-upload
          ref="uploadRef"
          name="files"
          multiple
          :file-list="fileList"
          :on-remove="handleRemove"
            :on-change="handleChange"
          :limit="9"
          :auto-upload="false"
          :on-exceed="handleExceed"
          :show-file-list="false">
            <el-button type="primary">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon><span class="pljh"
                    v-if="!$isMobile">{{props.uploadButtonText}}</span>
            </el-button>
        </el-upload>
       

        <!-- <div v-if="isUploading" class="progress-container">
            <div v-for="(file, index) in selectedFiles" :key="index" style="margin-top: 10px;">
                <span>{{ file.name }}</span>
                <el-progress :percentage="uploadProgress[index]"
                    :status="uploadProgress[index] === 100 ? 'success' : ''"></el-progress>
            </div>
        </div> -->
    </div>
</template>

<style scoped lang="scss">
.el-icon--upload {
    font-size: 26px;
}

.upload-container{
  position: relative;
}

.progress-container{
  position: absolute;
  bottom:0;
  left:23.5vw;
  width: 10vw;
}

</style>
